class Question < ActiveRecord::Base
  validates_presence_of :wording
  validates_presence_of :max_time
  
  has_many :answers, :dependent => :destroy
  has_and_belongs_to_many :categories
  has_many :included_questions
  has_many :questionnaires, :through => :included_questions
  belongs_to :user, :foreign_key => :creator_id
  
  after_update :save_answers
  
  def new_answer_attributes=(answer_attributes)
    answer_attributes.each_with_index do |attributes, order|
      attributes[:order] = order
      answers.build(attributes)
    end
  end

  def existing_answer_attributes=(answer_attributes)
    answers.reject(&:new_record?).each do |answer|
      attributes = answer_attributes[answer.id.to_s]
      if attributes
        answer.attributes = attributes
      else
        answers.delete(answer)
      end
    end
  end
  
  def save_answers
    answers.each_with_index do |answer, index|
      answer.order = index
      answer.save(false)
    end
  end
end
